{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 一、ndarray",
   "id": "b5d3646124a1c606"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 1.特性",
   "id": "2ba2c70669f2c2c6"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 多维性",
   "id": "78de070296e7a55e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T14:43:08.884556Z",
     "start_time": "2025-07-23T14:43:08.865555Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "a = np.array([1,2,3]) #\n",
    "\n",
    "print(type(a))\n",
    "print(a.ndim) #维度 1 "
   ],
   "id": "dfb33705ea1d83dd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n",
      "<class 'numpy.ndarray'>\n",
      "1\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-12T09:10:28.787951Z",
     "start_time": "2025-07-12T09:10:28.773496Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "a = np.array(1) #创建一维ndarray\n",
    "print(a)\n",
    "print(a.ndim) #维度 0"
   ],
   "id": "438f598f2dd41622",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "0\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 同质性",
   "id": "576febab9a1e47ab"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-12T09:13:52.510794Z",
     "start_time": "2025-07-12T09:13:52.494217Z"
    }
   },
   "cell_type": "code",
   "source": [
    "arr = np.array([1,2,3])\n",
    "print(arr.dtype)\n",
    "arr = np.array([\"1\",2,3.0])\n",
    "print( arr) #['1' '2' '3.0'] 不同的数据类型会转换为相同的\n",
    "print(arr.dtype)  #<U32\n",
    "arr = np.array([1,2,3.0])\n",
    "print(arr)  #[1. 2. 3.]"
   ],
   "id": "6f8ee72d6162814d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "int64\n",
      "['1' '2' '3.0']\n",
      "<U32\n",
      "[1. 2. 3.]\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 属性",
   "id": "8dcfedec677c47fb"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-12T09:21:54.351036Z",
     "start_time": "2025-07-12T09:21:54.338414Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# shape 数组的形状\n",
    "a = np.array([[1,2,3],[4,5,6]])\n",
    "print(a.shape) # (2,3)  \n",
    "print(type(a.shape)) #tuple\n",
    "# ndim\n",
    "print(a.ndim) #维度 2\n",
    "print(type(a.ndim)) # int\n",
    "\n",
    "# size\n",
    "print(a.size) #整体的长度 6\n",
    "print(type(a.size)) # int\n",
    "\n",
    "# dtype 类型\n",
    "print(a.dtype) # int64\n",
    "\n",
    "#转置 行列互换\n",
    "print(a.T)\n",
    "\n"
   ],
   "id": "f7aaa41f7a5e251c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2, 3)\n",
      "<class 'tuple'>\n",
      "2\n",
      "<class 'int'>\n",
      "6\n",
      "<class 'int'>\n",
      "int64\n",
      "[[1 4]\n",
      " [2 5]\n",
      " [3 6]]\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## ndarry创建",
   "id": "282835e7eadd0033"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "858e5691112e419a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-12T09:50:36.248464Z",
     "start_time": "2025-07-12T09:50:36.213197Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.基础构造: 适用于手动构建小规模数组或复制已有数据。\n",
    "a = np.array([1,2,3],dtype=np.float32)\n",
    "print(a) # [1. 2. 3.]\n",
    "arr2 = a.copy() # 复制,非相同指向\n",
    "print(arr2) # [1. 2. 3.]\n",
    "arr2[1] = 5\n",
    "print(a) #  [1. 2. 3.]\n",
    "print(arr2) # [1. 5. 3.]"
   ],
   "id": "122e5a5f1b103033",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1. 2. 3.]\n",
      "[1. 2. 3.]\n",
      "[1. 2. 3.]\n",
      "[1. 5. 3.]\n",
      "[[0. 0. 0.]\n",
      " [0. 0. 0.]]\n",
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]]\n",
      "[0 2 4 6 8]\n",
      "[[1. 0. 0.]\n",
      " [0. 1. 0.]\n",
      " [0. 0. 1.]]\n",
      "[[0.30912731 0.51313287 0.67051755]\n",
      " [0.30931907 0.36400053 0.30234864]]\n"
     ]
    },
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'data.txt'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mFileNotFoundError\u001B[0m                         Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[14], line 29\u001B[0m\n\u001B[0;32m     26\u001B[0m \u001B[38;5;28mprint\u001B[39m(a) \u001B[38;5;66;03m#[[0.5 0.2 0.3] [0.1 0.4 0.7]]\u001B[39;00m\n\u001B[0;32m     28\u001B[0m \u001B[38;5;66;03m# 6.高级构造方法:处理非结构化数据(如文件、字符串)或通过函数生成复杂数组。\u001B[39;00m\n\u001B[1;32m---> 29\u001B[0m a \u001B[38;5;241m=\u001B[39m \u001B[43mnp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mfromfile\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[38;5;124;43mdata.txt\u001B[39;49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43mdtype\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mnp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mfloat32\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m     30\u001B[0m \u001B[38;5;28mprint\u001B[39m(a)\n",
      "\u001B[1;31mFileNotFoundError\u001B[0m: [Errno 2] No such file or directory: 'data.txt'"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 2.预定义形状填充: 用于快速初始化固定形状的数组(如全0占位、全1初始化)。\n",
    "a = np.zeros((2,3)) #创建一个二维数组，形状为2行3列，元素全为0\n",
    "print(a) #[[0. 0. 0.][0. 0. 0.]]\n",
    "a = np.ones((2,3))\n",
    "print(a) #[[1. 1. 1.] [1. 1. 1.]]\n",
    "a = np.full((2,3),5) #填充5\n",
    "print(a) #[[5. 5. 5.] [5. 5. 5.]]\n",
    "a = np.empty((2,3)) #空，实际值为随机数，可能为0 不推荐\n",
    "print(a) #[[ 1.38777878e-17  1.11022302e-16  1.11022302e-16]]\n",
    "#zeros_like 形状和数据类型都相同，填充0\n",
    "a = np.zeros_like(np.array([1,2,3]))\n",
    "print(a) #[0. 0. 0."
   ],
   "id": "e53839e8a18ad20b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-12T10:00:05.292031Z",
     "start_time": "2025-07-12T10:00:05.281293Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 3.基于数值范围生成:生成数值序列，常用于模拟时间序列、坐标网格等。\n",
    "# arange 等差生生成\n",
    "a = np.arange(0,10,2) #生成[0,10)的序列，步长为2\n",
    "print(a) #[0 2 4 6 8]\n",
    "# linspace 等分数生成\n",
    "a = np.linspace(0,10,5) #生成[0,10]的序列，等分数为5]\n",
    "print(a) #[0. 2.5 5. 7.5 10.]\n",
    "# 对数间隔数列 [ 1.  9. 81.] 先将[0,4]等分三分 [0,2,4] 然后以三为低，求次方\n",
    "a = np.logspace(0,4,3,base=3)\n",
    "print(a)"
   ],
   "id": "453859bb04f1cadd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 2 4 6 8]\n",
      "[ 0.   2.5  5.   7.5 10. ]\n",
      "[ 1.  9. 81.]\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T15:56:46.172483Z",
     "start_time": "2025-07-13T15:56:46.156111Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 4.特殊矩阵生成: 数学运算专用(如线性代数中的单位矩阵)。\n",
    "a = np.eye(3) #生成单位矩阵\n",
    "print(a) #[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]\n"
   ],
   "id": "7a53776213fccbd5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 0. 0.]\n",
      " [0. 1. 0.]\n",
      " [0. 0. 1.]]\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T15:56:29.873508Z",
     "start_time": "2025-07-13T15:56:29.596420Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 5.随机数组生成:模拟实验数据、初始化神经网络权重等场景。\n",
    "a = np.random.rand(2,3) #生成二维数组，元素随机\n",
    "print(a) #[[0.5 0.2 0.3] [0.1 0.4 0.7]]"
   ],
   "id": "9af48fe99dd22c43",
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'np' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mNameError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[1], line 2\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;66;03m# 5.随机数组生成:模拟实验数据、初始化神经网络权重等场景。\u001B[39;00m\n\u001B[1;32m----> 2\u001B[0m a \u001B[38;5;241m=\u001B[39m \u001B[43mnp\u001B[49m\u001B[38;5;241m.\u001B[39mrandom\u001B[38;5;241m.\u001B[39mrand(\u001B[38;5;241m2\u001B[39m,\u001B[38;5;241m3\u001B[39m) \u001B[38;5;66;03m#生成二维数组，元素随机\u001B[39;00m\n\u001B[0;32m      3\u001B[0m \u001B[38;5;28mprint\u001B[39m(a) \u001B[38;5;66;03m#[[0.5 0.2 0.3] [0.1 0.4 0.7]]\u001B[39;00m\n",
      "\u001B[1;31mNameError\u001B[0m: name 'np' is not defined"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 6.高级构造方法:处理非结构化数据(如文件、字符串)或通过函数生成复杂数组。\n",
    "a = np.fromfile('../课件/data/data.txt',dtype=np.float32)\n",
    "print(a)"
   ],
   "id": "5b1a6bc20ac060ed"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 矩阵",
   "id": "64b9a9a986d93b66"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 名称      维度      示例              备注\n",
    "# 标量      0维      5, 3.14          单个数字，无行列\n",
    "# 向量      1维      [1, 2, 3]        只有行或列（一维数组）\n",
    "# 矩阵      2维      [[1, 2], [3, 4]] 严格的行列结构（二维表）\n",
    "# 张量      ≥3维     [[[1, 2], [3, 4]] 高阶数组（如RGB图像）"
   ],
   "id": "d5684f9ed9fed679"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T16:24:09.733976Z",
     "start_time": "2025-07-13T16:24:09.725070Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "#零矩阵 全是0\n",
    "a = np.zeros((2,3))\n",
    "print(a)\n",
    "#单位矩阵 对角线是1，其他是0\n",
    "a = np.eye(3)\n",
    "print(a)\n",
    "a = np.eye(3,4)\n",
    "print(a)\n",
    "#对角矩阵 对角线是输入的数组(非零)，其他是0\n",
    "a = np.diag([1,2,3])\n",
    "print(a)\n",
    "#对称矩阵 行列转换相同\n",
    "A = np.array([[1, 2, 3], [2, 5, 6], [3, 6, 9]])\n",
    "print(a)\n",
    "# 验证对称性\n",
    "print(np.allclose(A, A.T))  # 输出 True\n",
    "\n",
    "# 生成随机对称矩阵\n",
    "B = np.random.rand(3, 3)\n",
    "B_symmetric = (B + B.T) / 2  # 强制对称， 可能会改变数值，数值为(a + a对称数)/2\n",
    "print(B)\n",
    "print(B_symmetric)\n",
    "print(np.allclose(B_symmetric, B_symmetric.T))"
   ],
   "id": "553976a860558fd8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0. 0.]\n",
      " [0. 0. 0.]]\n",
      "[[1. 0. 0.]\n",
      " [0. 1. 0.]\n",
      " [0. 0. 1.]]\n",
      "[[1. 0. 0. 0.]\n",
      " [0. 1. 0. 0.]\n",
      " [0. 0. 1. 0.]]\n",
      "[[1 0 0]\n",
      " [0 2 0]\n",
      " [0 0 3]]\n",
      "[[1 0 0]\n",
      " [0 2 0]\n",
      " [0 0 3]]\n",
      "True\n",
      "[[0.12210029 0.2386733  0.55006586]\n",
      " [0.94269618 0.83356442 0.99742281]\n",
      " [0.15582597 0.69959948 0.08451368]]\n",
      "[[0.12210029 0.59068474 0.35294591]\n",
      " [0.59068474 0.83356442 0.84851114]\n",
      " [0.35294591 0.84851114 0.08451368]]\n",
      "True\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T16:32:43.254298Z",
     "start_time": "2025-07-13T16:32:43.245959Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 生成指定范围随机数，随机数为[0,1)\n",
    "B = np.random.rand(3, 3)\n",
    "print( B)\n",
    "#生成指定范围整形随机数\n",
    "a = np.random.randint(0,10,(2,3))\n",
    "print(a)\n",
    "#生成指定范围浮点数\n",
    "a = np.random.uniform(0,10,(2,3))\n",
    "print(a)\n",
    "# 生成正态分布随机数, 均值为0，标准差为1,行为2，列为3，中间概率 高，边缘概率 低\n",
    "a = np.random.normal(0,1,(2,3))\n",
    "print(a)"
   ],
   "id": "1549c6f0d777fba3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.73817649 0.45376425 0.57493887]\n",
      " [0.73418488 0.67013441 0.15834021]\n",
      " [0.10654704 0.09152476 0.39800974]]\n",
      "[[8 8 3]\n",
      " [9 1 5]]\n",
      "[[1.50940568 7.08052941 0.18477372]\n",
      " [8.41977113 0.26198662 2.88088529]]\n",
      "[[-0.15987775  1.10761801 -0.46285876]\n",
      " [ 0.0181105  -0.70964936 -1.96764874]]\n",
      "[[0.5488135  0.71518937 0.60276338]\n",
      " [0.54488318 0.4236548  0.64589411]]\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T16:32:58.054752Z",
     "start_time": "2025-07-13T16:32:58.041583Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#设置随机种子，使得每次生成的随机数相同\n",
    "np.random.seed(0)\n",
    "print(np.random.rand(2,3))"
   ],
   "id": "499a8cac37ffa4ac",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.5488135  0.71518937 0.60276338]\n",
      " [0.54488318 0.4236548  0.64589411]]\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 数据类型\n",
    "数据类型      说明\n",
    "-----------------------------------------------------------\n",
    "bool         布尔类型\n",
    "int8、uint8  有符号([-128,127])、无符号([0,255])的8位（1字节）整型\n",
    "int16、uint16 有符号、无符号的16位（2字节）整型\n",
    "int32、uint32 有符号、无符号的32位（4字节）整型\n",
    "int64、uint64 有符号、无符号的64位（8字节）整型\n",
    "float16      半精度浮点型\n",
    "float32      单精度浮点型\n",
    "float64      双精度浮点型\n",
    "complex64    用两个32位浮点数表示的复数\n",
    "complex128   用两个64位浮点数表示的复数"
   ],
   "id": "ac5d490e2f3310c2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T16:38:58.809640Z",
     "start_time": "2025-07-13T16:38:58.798998Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#布尔类型\n",
    "a = np.array([True,False,True])\n",
    "print(a) #[ True False  True]\n",
    "#使用数字定义布尔类型，非0都是true\n",
    "a = np.array([1,0,3],dtype=bool)\n",
    "print(a) #[ True False  True]"
   ],
   "id": "854b560da5166b47",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ True False  True]\n",
      "[ True False  True]\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T16:41:03.184138Z",
     "start_time": "2025-07-13T16:41:03.161592Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#整数类型\n",
    "a = np.array([1,2,3],dtype=np.int64)\n",
    "print(a)\n",
    "print(a.dtype)\n",
    "#越界\n",
    "a = np.array([1,2,127],dtype=np.int8) #[-128,127]\n",
    "print(a)\n",
    "a = np.array([1,2,300],dtype=np.int8) #[-128,127]\n",
    "print(a) # Python integer 300 out of bounds for int8"
   ],
   "id": "c692baa17dfa4d46",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n",
      "int64\n"
     ]
    },
    {
     "ename": "OverflowError",
     "evalue": "Python integer 128 out of bounds for int8",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mOverflowError\u001B[0m                             Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[24], line 6\u001B[0m\n\u001B[0;32m      4\u001B[0m \u001B[38;5;28mprint\u001B[39m(a\u001B[38;5;241m.\u001B[39mdtype)\n\u001B[0;32m      5\u001B[0m \u001B[38;5;66;03m#越界\u001B[39;00m\n\u001B[1;32m----> 6\u001B[0m a \u001B[38;5;241m=\u001B[39m \u001B[43mnp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43marray\u001B[49m\u001B[43m(\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m1\u001B[39;49m\u001B[43m,\u001B[49m\u001B[38;5;241;43m2\u001B[39;49m\u001B[43m,\u001B[49m\u001B[38;5;241;43m128\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m,\u001B[49m\u001B[43mdtype\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mnp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mint8\u001B[49m\u001B[43m)\u001B[49m \u001B[38;5;66;03m#[-128,127]\u001B[39;00m\n\u001B[0;32m      7\u001B[0m \u001B[38;5;28mprint\u001B[39m(a)\n\u001B[0;32m      8\u001B[0m a \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39marray([\u001B[38;5;241m1\u001B[39m,\u001B[38;5;241m2\u001B[39m,\u001B[38;5;241m300\u001B[39m],dtype\u001B[38;5;241m=\u001B[39mnp\u001B[38;5;241m.\u001B[39mint8) \u001B[38;5;66;03m#[-128,127]\u001B[39;00m\n",
      "\u001B[1;31mOverflowError\u001B[0m: Python integer 128 out of bounds for int8"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:12:21.570367Z",
     "start_time": "2025-08-20T09:12:21.524471Z"
    }
   },
   "cell_type": "code",
   "source": [
    "dp1 = [1,2,3]\n",
    "dp2 = [4,5,6]\n",
    "print(dp1+dp2)"
   ],
   "id": "fe6c015363961704",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 索引与切片\n",
   "id": "d71934105e178de4"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 索引/切片类型      描述/用法\n",
    "# -----------------------------------------------------------------------\n",
    "# 基本索引          通过整数索引直接访问元素。索引从 0 开始（修正：O→0）。\n",
    "# 行/列切片         使用冒号 `:` 切片语法选择行或列的子集（如 `arr[1:3]`）。\n",
    "# 连续切片          从起始索引到结束索引按步长切片（如 `arr[start:stop:step]`）。\n",
    "# 使用 slice 函数    通过 `slice(start, stop, step)` 定义切片规则（需注意函数名小写）。\n",
    "# 布尔索引          通过布尔条件筛选满足条件的元素。支持逻辑运算符 `&`（与）、`|`（或）。"
   ],
   "id": "a040d44271225946"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T18:51:13.738199Z",
     "start_time": "2025-07-15T18:51:13.446518Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#索引\n",
    "#一维数组\n",
    "# a = np.random.randint(0, 10, 10)\n",
    "a = np.array([0, 2, 3, 8, 1, 3, 3, 3, 7, 0])\n",
    "print(a) #[0 2 3 8 1 3 3 3 7 0]\n",
    "print(a[0]) #0\n",
    "print(a[:]) #[0 2 3 8 1 3 3 3 7 0]\n",
    "print(a[5:]) #[3 3 3 7 0]\n",
    "print(a[0:5]) #[0 2 3 8 1] \n",
    "print(a[::2]) #[0 3 1 7] [start, stop, step] 不包括stop\n",
    "#布尔索引\n",
    "print(a[a>3])\n",
    "#多条件\n",
    "print(a[(a>3) & (a<7)])\n",
    "\n",
    "#slice 目前作用和:相同\n",
    "print(a[slice(1, 5)]) #[2 3 8 1]\n",
    "#二维数组slice\n",
    "a = np.random.randint(0, 10, (5, 5))\n",
    "print(a)\n",
    "#slice\n",
    "print(a[slice(1, 3), slice(1, 3)])"
   ],
   "id": "2ebfc37a932b239a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 2 3 8 1 3 3 3 7 0]\n",
      "0\n",
      "[0 2 3 8 1 3 3 3 7 0]\n",
      "[3 3 3 7 0]\n",
      "[0 2 3 8 1]\n",
      "[0 3 1 3 7]\n",
      "[8 7]\n",
      "[]\n",
      "[2 3 8 1]\n",
      "[[7 8 1 5 6]\n",
      " [4 5 7 9 8]\n",
      " [8 3 9 7 7]\n",
      " [1 3 4 5 0]\n",
      " [6 1 1 8 3]]\n",
      "[[5 7]\n",
      " [3 9]]\n"
     ]
    }
   ],
   "execution_count": 27
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n",
      "0\n",
      "[ 0  5 10 15 20]\n",
      "[0 1 2 3 4]\n",
      "[[0 1]\n",
      " [5 6]]\n",
      "[11 12 13 14 15 16 17 18 19 20 21 22 23 24]\n",
      "[18 19]\n",
      "[13 14]\n"
     ]
    }
   ],
   "execution_count": 46,
   "source": [
    "#二维数组\n",
    "a = np.random.randint(0, 10, (5, 5))\n",
    "#固定的二维\n",
    "a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])\n",
    "print(a) \n",
    "print(a[0, 0]) #0 \n",
    "print(a[:, 0]) #[0 5 10 15 20] 获取第一列\n",
    "print(a[0, :]) # [0 1 2 3 4]\n",
    "print(a[0:2, 0:2]) #[[0 1] #[5 6]]\n",
    "#布尔 结果是一维\n",
    "print(a[a>10])#[11 12 13 14 15 16 17 18 19 20 21 22 23 24]\n",
    "#先切片 + 布尔\n",
    "print(a[3][a[2]>12]) #[18 19] 第三行，且满足第二列大于12的列，这是[3,4]列\n",
    "print(a[2][a[2]>12]) #[13 14] "
   ],
   "id": "9557985d80662969"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## ndarry运算\n",
   "id": "63179efa92d64b25"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5 6 7 8 9]\n",
      "[[1 2 3]\n",
      " [4 5 6]\n",
      " [7 8 9]]\n",
      "[[ 2  4  6]\n",
      " [ 8 10 12]\n",
      " [14 16 18]]\n",
      "[[0 0 0]\n",
      " [0 0 0]\n",
      " [0 0 0]]\n",
      "[[ 1  4  9]\n",
      " [16 25 36]\n",
      " [49 64 81]]\n",
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]\n",
      " [1. 1. 1.]]\n",
      "[1, 2, 3, 4, 5, 6]\n",
      "<generator object <genexpr> at 0x000001720E1593F0>\n",
      "[5, 7, 9]\n",
      "[[5 6 7]\n",
      " [6 7 8]\n",
      " [7 8 9]]\n"
     ]
    }
   ],
   "execution_count": 61,
   "source": [
    "#相加\n",
    "a = np.arange(1, 10)\n",
    "print(a)\n",
    "#变为二维 从上往下，左往右填充，长度和二维必须一致，否则报错\n",
    "a = a.reshape(3, 3)\n",
    "print(a) #[[1 2 3][4 5 6][7 8 9]]\n",
    "print(a+a) #[[2 4 6][8 10 12][14 16 18]]\n",
    "print(a-a) ##[[0 0 0][0 0 0][0 0 0]]\n",
    "print(a*a) ##[[ 1  4  9][16 25 36][49 64 81]]\n",
    "print(a/a) #[1. 1. 1.]\n",
    "\n",
    "#java数组相加\n",
    "a = [1,2,3]\n",
    "b = [4,5,6]\n",
    "print(a+b) #[1, 2, 3, 4, 5, 6] 拼接\n",
    "print(a[i]+b[i] for i in range(len(a)))\n",
    "print([a[i]+b[i] for i in range(len(a))]) #[5, 7, 9] 达到类似numpy效果\n"
   ],
   "id": "eb0d215daf29f142"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5 6 7]\n",
      " [6 7 8]\n",
      " [7 8 9]]\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "operands could not be broadcast together with shapes (3,) (1,2) ",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mValueError\u001B[0m                                Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[63], line 11\u001B[0m\n\u001B[0;32m      9\u001B[0m a \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39marray([\u001B[38;5;241m1\u001B[39m,\u001B[38;5;241m2\u001B[39m,\u001B[38;5;241m3\u001B[39m])\n\u001B[0;32m     10\u001B[0m b \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39marray([[\u001B[38;5;241m4\u001B[39m,\u001B[38;5;241m5\u001B[39m]])\n\u001B[1;32m---> 11\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[43ma\u001B[49m\u001B[38;5;241;43m+\u001B[39;49m\u001B[43mb\u001B[49m)\n",
      "\u001B[1;31mValueError\u001B[0m: operands could not be broadcast together with shapes (3,) (1,2) "
     ]
    }
   ],
   "execution_count": 63,
   "source": [
    "#广播机制 1.获取形状 2.是否可广播\n",
    "a = np.array([1,2,3])\n",
    "b = np.array([[4],[5],[6]])\n",
    "# a转为 [[1,2,3],[1,2,3],[1,2,3]]\n",
    "# b转为 [[4,4,4],[5,5,5],[6,6,6]]\n",
    "print(a+b) #[[5 6 7][6 7 8] [7 8 9]]\n",
    "\n",
    "#不可广播\n",
    "a = np.array([1,2,3])\n",
    "b = np.array([[4,5]])\n",
    "print(a+b) #ValueError: operands could not be broadcast together with shapes (3,) (1,2)"
   ],
   "id": "93b12097e52201e2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:14:36.287175Z",
     "start_time": "2025-08-20T09:14:35.506177Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "# 矩阵计算\n",
    "a = np.array([[1,2],[3,4]])\n",
    "# b = np.array([[1,2],[3,4]])\n",
    "b = np.array([[5,6],[7,8]])\n",
    "print(a * b) #[[1 4][9 16]]\n",
    "print(a @ b) #[[7 10][15 22]] 计算方式：所在位置的行和所在位置的列每个位置相乘的和\n",
    "# 比如 [1 2] @ [1 2] = [1*1 + 2*3 1*2 + 2*4] = [7 10]\n",
    "#     [3 4]   [3 4] = [3*1 + 4*3 3*2 + 4*4] = [15 22]\n",
    "#对于[0][0] 他的行是[1,2] 列是 [1,3] 所以结果: 1*1 + 2*3 = 7\n",
    "# 对于[0][1] 他的行是[1,2] 列是 [2,4] 所以结果: 1*2 + 2*4 = 10\n",
    "# 对于[1][0] 他的行是[3,4] 列是 [1,3] 所以结果: 3*1 + 4*3 = 15\n",
    "# 对于[1][1] 他的行是[3,4] 列是 [2,4] 所以结果: 3*2 + 4*4 = 22\n",
    "\n",
    "#矩阵介绍：https://www.cnblogs.com/yansc/p/15629361.html\n",
    "#矩阵乘法条件：第一个矩阵的列（的个数）要等于第二个矩阵的行（个数）  2*3  dot  3*2 == 2*2\n",
    "a = np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
    "b = np.array([[1,1,1],[1,1,1],[1,1,1]])\n",
    "print(a @ b)\n",
    " "
   ],
   "id": "de3a915df2081efa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 5 12]\n",
      " [21 32]]\n",
      "[[19 22]\n",
      " [43 50]]\n",
      "[[ 6  6  6]\n",
      " [15 15 15]\n",
      " [24 24 24]]\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 2.函数",
   "id": "2f7ca5b475991826"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.1基本函数",
   "id": "e523f172d7bfa55d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:03:28.423824Z",
     "start_time": "2025-07-14T18:03:28.410165Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "#计算平凡根\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.sqrt(a)) #[1.         1.41421356 1.73205081 2.         2.23606798]\n",
    "print(np.sqrt(4)) #2\n",
    "#计算指数 e^x 计算方式：e^x\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.exp(a))\n",
    "print(np.exp(1)) #2.718281828459045\n",
    "\n",
    "# 计算自然对数 ln(x) e的幂 计算方式：e的多少次方等于x\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.log(a))\n",
    "print(np.log(2.718281828459045)) #1.0\n",
    "print(np.log(2)) #0.6931471805599453\n",
    "print(np.log(4)) #1.3862943611198906\n"
   ],
   "id": "8f31c17af0f6af99",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.         1.41421356 1.73205081 2.         2.23606798]\n",
      "2.0\n",
      "[  2.71828183   7.3890561   20.08553692  54.59815003 148.4131591 ]\n",
      "2.718281828459045\n",
      "[0.         0.69314718 1.09861229 1.38629436 1.60943791]\n",
      "1.0\n",
      "0.6931471805599453\n",
      "1.3862943611198906\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:09:08.442104Z",
     "start_time": "2025-07-14T18:09:08.422126Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算正弦和余弦值\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.sin(a))\n",
    "print(np.cos(a))\n",
    "print(np.sin(np.pi/2)) #1.0"
   ],
   "id": "3440b334c22a2905",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 0.84147098  0.90929743  0.14112001 -0.7568025  -0.95892427]\n",
      "[ 0.54030231 -0.41614684 -0.9899925  -0.65364362  0.28366219]\n",
      "1.0\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:09:31.121373Z",
     "start_time": "2025-07-14T18:09:31.108395Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#绝对值\n",
    "a = np.array([-1,-2,-3,-4,-5])\n",
    "print(np.abs(a))\n",
    "print(np.abs(-1))"
   ],
   "id": "db5baa1a4c65f742",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5]\n",
      "1\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:10:12.614607Z",
     "start_time": "2025-07-14T18:10:12.609067Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#计算幂\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.power(a,2))\n"
   ],
   "id": "2a86b0cbbf75bdf6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1  4  9 16 25]\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:15:17.153660Z",
     "start_time": "2025-07-14T18:15:17.147149Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#四舍五入\n",
    "a = np.array([1.1,2.2,3.3,4.4,5.5])\n",
    "print(np.round(a))\n",
    "a= np.round(a)\n",
    "print(a[a>4])\n",
    "\n",
    "#向上取整\n",
    "a = np.array([1.1,2.2,3.3,4.4,5.5])\n",
    "print(np.ceil(a))\n",
    "\n",
    "#向下取整\n",
    "a = np.array([1.1,2.2,3.3,4.4,5.5])\n",
    "print(np.floor(a))"
   ],
   "id": "6d24fec8a9d11f3e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1. 2. 3. 4. 6.]\n",
      "[6.]\n",
      "[2. 3. 4. 5. 6.]\n",
      "[1. 2. 3. 4. 5.]\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:16:23.454716Z",
     "start_time": "2025-07-14T18:16:23.435993Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 检查缺失值NAN np.nan代表NAN\n",
    "a = np.array([1,2,3,4,5,np.nan])\n",
    "print(np.isnan(a)) #[False False False False False  True]\n",
    "print(np.nan) # nan\n",
    "print(np.isnan(np.nan)) # True"
   ],
   "id": "46e569bd08331b99",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False False False False False  True]\n",
      "nan\n",
      "True\n"
     ]
    }
   ],
   "execution_count": 27
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.2 统计函数",
   "id": "422acdd6d37c8b61"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:27:05.145507Z",
     "start_time": "2025-07-14T18:27:05.140657Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# arr = np.random.randint(1,10,10)\n",
    "arr = np.array([1,2,3,4,5])\n",
    "print(arr)\n",
    "# 求和\n",
    "print(np.sum(arr))\n",
    "# 求平均值\n",
    "print(np.mean(arr))\n",
    "# 中位数\n",
    "print(np.median(arr))\n",
    "# 求最大值\n",
    "print(np.max(arr))\n",
    "# 求最小值\n",
    "print(np.min(arr))\n",
    "# 最大值位置\n",
    "print(np.argmax(arr))\n",
    "# 最小值位置\n",
    "print(np.argmin(arr))\n",
    "\n",
    "\n",
    "# 方差\n",
    "#计算方式：1. 求和，求平均值，求平方，求和/数量\n",
    "# (1-3) ^2 + (2-3)^2 + (3-3)^2 + (4-3)^2 + (5-3)^2 / 5 = 10/5 = 2\n",
    "print(np.var([1,2,3,4,5])) #2.0\n",
    "\n",
    "#标准差\n",
    "#计算方式：1. 求和，求平均值，求平方，求和，求和/数量,开根号\n",
    "print(np.std([1,2,3,4,5])) #1.4142135623730951\n",
    "\n"
   ],
   "id": "9fcd47d68d3dcafc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5]\n",
      "15\n",
      "3.0\n",
      "3.0\n",
      "5\n",
      "1\n",
      "1.4142135623730951\n",
      "2.0\n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T18:59:57.824369Z",
     "start_time": "2025-07-14T18:59:57.811493Z"
    }
   },
   "cell_type": "code",
   "source": [
    "arr = np.array([1,2,3,4,5])\n",
    "# 分位数 介绍: 百分比\n",
    "print(np.percentile(arr, 50)) ##3.0 中位数\n",
    "print(np.percentile(arr, 0)) ##1.0\n",
    "print(np.percentile(arr, 25)) #2.0\n",
    "print(np.percentile(arr, 75)) #4.0\n",
    "print(np.percentile(arr, 100)) #5.0\n",
    "print(np.percentile(arr, 22)) #1.88 计算公式: 22/100 * (5-1) + 1 = 1.88\n",
    "\n",
    "print(np.percentile([1,2,100], 50)) #2.0 计算公式:\n",
    "print(np.percentile([1,2,100], 40)) #前百分之40，结果 1.8 计算公式:2 *[1 - (40/50)] + 1 * [1-(10/50)]\n",
    "print(np.median([1,2,100])) #2.0\n",
    "\n",
    "print(np.percentile([1,4,8,10],25)) #3.25\n",
    "# 吧所有间距认为是1，这里有三个间距所以分为三等分，25*3/100 = 0.75\n",
    "# 1 + (4 - 1)*0.75 = 3.25\n",
    "# 开始 + 间距 * 间距占比"
   ],
   "id": "aa964b6bb134bd4f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.0\n",
      "1.0\n",
      "2.0\n",
      "4.0\n",
      "5.0\n",
      "1.88\n",
      "2.0\n",
      "1.8\n",
      "2.0\n",
      "3.25\n"
     ]
    }
   ],
   "execution_count": 52
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-14T19:02:54.142114Z",
     "start_time": "2025-07-14T19:02:54.123719Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 累积和，累积积\n",
    "#累积和 从1开始累加\n",
    "print(np.cumsum([1,2,3,4])) #[ 1  3  6 10]\n",
    "#累积积 从1开始累乘\n",
    "print(np.cumprod([1,2,3,4])) ##[ 1  2  6 24]\n"
   ],
   "id": "f08ba4cec4ccfdfa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1  3  6 10]\n",
      "[ 1  2  6 24]\n"
     ]
    }
   ],
   "execution_count": 54
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.3比较函数\n",
   "id": "5e2490f6a37c97be"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-31T09:07:30.942514Z",
     "start_time": "2025-07-31T09:07:30.919515Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "# 是否大大于 前面是否大于后面\n",
    "print(np.greater([1,2,3,5], [1,2,3,4]))\n",
    "print(np.greater([1,2,3,4], 2))\n",
    "\n",
    "# 是否小于\n",
    "print(np.less([1,2,3,5], [1,2,3,4]))\n",
    "print(np.less([1,2,3,4], 2))\n",
    "\n",
    "# 是否相等\n",
    "print(np.equal([1,2,3,5], [1,2,3,4]))\n",
    "print(np.equal([1,2,3,4], 2))\n",
    "\n",
    "#在定义条件\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.where(a>2,a,2)) #[2 2 3 4 5]\n",
    "print(np.where(a>2,\">2\",\"<=2\")) #['<=2' '<=2' '>2' '>2' '>2']\n",
    "#嵌套\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.where(a>2,\"大于2\",np.where(a>1,\"大于1\",\"不大于1\")))\n",
    "\n",
    "#selet\n",
    "a = np.array([1,2,3,4,5])\n",
    "print(np.select([a>2,a>1],[a,a+1])) #[0 3 3 4 5] 全不满足则直接为\n",
    "print(np.select([a>2,a>1,a<=1],[a,a+1,a]))#[1 2 3 4 5]\n",
    "#defalut\n",
    "print(np.select([a>2,a>1],[a,a+1],default=a)) #[1 3 3 4 5]"
   ],
   "id": "49269743d7a00a29",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False False False  True]\n",
      "[False False  True  True]\n",
      "[False False False False]\n",
      "[ True False False False]\n",
      "[ True  True  True False]\n",
      "[False  True False False]\n",
      "[2 2 3 4 5]\n",
      "['<=2' '<=2' '>2' '>2' '>2']\n",
      "['不大于1' '大于1' '大于2' '大于2' '大于2']\n",
      "[0 3 3 4 5]\n",
      "[1 3 3 4 5]\n",
      "[1 3 3 4 5]\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T18:29:39.643571Z",
     "start_time": "2025-07-15T18:29:39.637061Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#排序函数\n",
    "# 1. np.sort(array) 不改变原数组\n",
    "a = np.array([1,3,3,2,2,5])\n",
    "print(np.sort(a)) #[1 2 2 3 3 5]\n",
    "# 2.array.sort() 改变原数组\n",
    "b = np.array([[1,3,2],[2,2,1]])\n",
    "b.sort()\n",
    "print( b)\n",
    "\n",
    "#索引排序\n",
    "a = np.array([1,3,4,2,6,5])\n",
    "print(np.argsort(a)) #[0 3 1 2 5 4]\n"
   ],
   "id": "40a8bd003d67bf98",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 2 3 3 5]\n",
      "[[1 2 3]\n",
      " [1 2 2]]\n",
      "[0 3 1 2 5 4]\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T18:45:18.817143Z",
     "start_time": "2025-07-15T18:45:18.792481Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#去重 + 排序\n",
    "a = np.array([1,2,3,3,2,1])\n",
    "print(np.unique(a))  #[1 2 3]\n",
    "\n",
    "#拼接 类似python的默认数组相加\n",
    "a = np.array([1,2,3])\n",
    "b = np.array([4,5,6])\n",
    "print(np.concatenate([a,b])) #[1 2 3 4 5 6]\n",
    "\n",
    "#分割\n",
    "a = np.array([1,2,3,4,5,6])\n",
    "print(np.split(a,2)) #[array([1, 2, 3]), array([4, 5, 6])]\n",
    "#不等分则报错\n",
    "# print(np.split(a,4)) #ValueError: array split does not result in an equal division\n",
    "#按照位置切分\n",
    "print(np.split(a,[2,4])) #[array([1, 2]), array([3, 4]), array([5, 6])]\n",
    "print(np.split(a,[1,5])) #[array([1]), array([2, 3, 4, 5]), array([6])]\n",
    "\n",
    "#调整数组形状\n",
    "a = np.array([1,2,3,4,5,6])\n",
    "print(a.reshape(2,3)) #[[1 2 3][4 5 6]]\n",
    "print(a.reshape(3,2)) #[[1 2][3 4][5 6]]\n",
    "# a = np.array([1,2,3,4,5,6,7])\n",
    "print(a.reshape(3,-1))#-1表示自动计算,3行x列"
   ],
   "id": "abede8dd9f279bd1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n",
      "[1 2 3 4 5 6]\n",
      "[array([1, 2, 3]), array([4, 5, 6])]\n",
      "[array([1, 2]), array([3, 4]), array([5, 6])]\n",
      "[array([1]), array([2, 3, 4, 5]), array([6])]\n",
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "cannot reshape array of size 7 into shape (3,newaxis)",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mValueError\u001B[0m                                Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[26], line 24\u001B[0m\n\u001B[0;32m     22\u001B[0m \u001B[38;5;28mprint\u001B[39m(a\u001B[38;5;241m.\u001B[39mreshape(\u001B[38;5;241m3\u001B[39m,\u001B[38;5;241m2\u001B[39m)) \u001B[38;5;66;03m#[[1 2][3 4][5 6]]\u001B[39;00m\n\u001B[0;32m     23\u001B[0m a \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39marray([\u001B[38;5;241m1\u001B[39m,\u001B[38;5;241m2\u001B[39m,\u001B[38;5;241m3\u001B[39m,\u001B[38;5;241m4\u001B[39m,\u001B[38;5;241m5\u001B[39m,\u001B[38;5;241m6\u001B[39m,\u001B[38;5;241m7\u001B[39m])\n\u001B[1;32m---> 24\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[43ma\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mreshape\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m3\u001B[39;49m\u001B[43m,\u001B[49m\u001B[38;5;241;43m-\u001B[39;49m\u001B[38;5;241;43m1\u001B[39;49m\u001B[43m)\u001B[49m)\u001B[38;5;66;03m#-1表示自动计算,3行x列\u001B[39;00m\n",
      "\u001B[1;31mValueError\u001B[0m: cannot reshape array of size 7 into shape (3,newaxis)"
     ]
    }
   ],
   "execution_count": 26
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 综合案例",
   "id": "f6f3e9958e2740a0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T16:24:55.616354Z",
     "start_time": "2025-07-16T16:24:55.596771Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "# 20-21\n",
    "#题目 1：温度数据分析\n",
    "# 题目：某城市一周的最高气温（℃）为 [28, 30, 29, 31, 32, 30, 29]。  \n",
    "# •\t计算平均气温、最高气温和最低气温。  \n",
    "# •\t找出气温超过 30℃ 的天数。  \n",
    "ar = np.array([28, 30, 29, 31, 32, 30, 29])\n",
    "print(np.mean(ar))\n",
    "print(np.max(ar))\n",
    "print(np.min(ar))\n",
    "print(len(ar[ar>30]))#过滤出满足条件的数据，然后获取长度\n",
    "print(np.cumsum(np.select([ar>30],[1],default=0))[-1]) #满足为1，否则为0，然后累加，最后取最后一个\n",
    "print(np.cumsum(np.where(ar>30,1,0))[-1]) #满足为1，否则为0，然后累加，最后取最后一个\n"
   ],
   "id": "831863d2c53b4bb8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "29.857142857142858\n",
      "32\n",
      "28\n",
      "2\n",
      "2\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T16:52:54.472613Z",
     "start_time": "2025-07-16T16:52:54.453921Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 2：学生成绩统计\n",
    "# 题目：某班级 5 名学生的数学成绩为 [85, 90, 78, 92, 88]。  \n",
    "# •\t计算成绩的平均分、中位数和标准差。  \n",
    "# •\t将成绩转换为百分制（假设满分为 10）。  \n",
    "import numpy as np\n",
    "ar = np.array([85, 90, 78, 92, 88])\n",
    "print(np.mean(ar))\n",
    "print(np.median(ar))\n",
    "print(np.std(ar))\n",
    "print(ar/10)"
   ],
   "id": "b33cec08875abdcd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "86.6\n",
      "88.0\n",
      "4.882622246293481\n",
      "[8.5 9.  7.8 9.2 8.8]\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T16:54:03.329607Z",
     "start_time": "2025-07-16T16:54:03.313488Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 3：矩阵运算\n",
    "# 题目：给定矩阵 A = [[1, 2], [3, 4]] 和 B = [[5, 6], [7, 8]]。  \n",
    "# •\t计算 A + B 和 A * B（逐元素乘法）。  \n",
    "# •\t计算 A 和 B 的矩阵乘法（点积）。  \n",
    "import numpy as np\n",
    "A = np.array([[1, 2], [3, 4]])\n",
    "B = np.array([[5, 6], [7, 8]])\n",
    "print(A + B)\n",
    "print(A * B)\n",
    "print(A @ B)\n"
   ],
   "id": "182b68268b1fd89c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 6  8]\n",
      " [10 12]]\n",
      "[[ 5 12]\n",
      " [21 32]]\n",
      "[[19 22]\n",
      " [43 50]]\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-31T09:52:55.447957Z",
     "start_time": "2025-07-31T09:52:55.365953Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 4：随机数据生成\n",
    "# 题目：生成一个 (3, 4) 的随机整数数组，范围 [0, 10)。  \n",
    "# •\t计算每列的最大值和每行的最小值。  \n",
    "# •\t将数组中的所有奇数替换为 -1。  \n",
    "import numpy as np\n",
    "np.random.seed(0)\n",
    "ar = np.random.randint(0, 10, (3, 4))\n",
    "print(ar)\n",
    "print(np.max(ar, axis=1))\n",
    "print(np.min(ar, axis=0))\n",
    "print(np.select([ar%2==1],[-1],default=ar))\n",
    "print(np.where(ar%2==1, -1, ar))\n"
   ],
   "id": "10ad512e0d18458e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5 0 3 3]\n",
      " [7 9 3 5]\n",
      " [2 4 7 6]]\n",
      "[5 9 7]\n",
      "[2 0 3 3]\n",
      "[[-1  0 -1 -1]\n",
      " [-1 -1 -1 -1]\n",
      " [ 2  4 -1  6]]\n",
      "[[-1  0 -1 -1]\n",
      " [-1 -1 -1 -1]\n",
      " [ 2  4 -1  6]]\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:05:51.180561Z",
     "start_time": "2025-07-16T17:05:51.163204Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 5：数组变形\n",
    "# 题目：创建一个 1 到 12 的一维数组，并转换为 (3, 4) 的二维数组。  \n",
    "# •\t计算每行的和与每列的平均值。  \n",
    "# •\t将数组展平为一维数组。  \n",
    "# \n",
    "import numpy as np\n",
    "ar = np.arange(1, 13).reshape(3, 4)\n",
    "print(ar)\n",
    "print(np.sum(ar, axis=1))\n",
    "print(np.mean(ar, axis=0))\n",
    "print(np.reshape(ar, -1))\n",
    "print(np.reshape(ar, 12)) #11报错,单个代表是向量二维 "
   ],
   "id": "c7f166786f5b0916",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2  3  4]\n",
      " [ 5  6  7  8]\n",
      " [ 9 10 11 12]]\n",
      "[10 26 42]\n",
      "[5. 6. 7. 8.]\n",
      "[ 1  2  3  4  5  6  7  8  9 10 11 12]\n",
      "[ 1  2  3  4  5  6  7  8  9 10 11 12]\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:09:46.750575Z",
     "start_time": "2025-07-16T17:09:46.738575Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 6：布尔索引\n",
    "# 题目：生成一个 (5, 5) 的随机数组，范围 [0, 20)。  \n",
    "# •\t找出数组中大于 10 的元素。  \n",
    "# •\t将所有大于 10 的元素替换为 0。 \n",
    "# \n",
    "import numpy as np\n",
    "ar = np.random.randint(0, 20, (5, 5))\n",
    "print(ar)\n",
    "print(ar[ar>10]) #[12 14 17 13 19 16 19 15 15 18 17 19 19 19 14]\n",
    "print(np.where(ar>10, 0, ar))\n",
    "ar[ar>10] = 0\n",
    "print(ar)\n"
   ],
   "id": "ba04432db925c5dc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 5  9  3  0  5]\n",
      " [ 0 17 18  4  2]\n",
      " [16  3  2 10 13]\n",
      " [16  7  9  0 10]\n",
      " [18 11  2  2  3]]\n",
      "[17 18 16 13 16 18 11]\n",
      "[[ 5  9  3  0  5]\n",
      " [ 0  0  0  4  2]\n",
      " [ 0  3  2 10  0]\n",
      " [ 0  7  9  0 10]\n",
      " [ 0  0  2  2  3]]\n",
      "[[ 5  9  3  0  5]\n",
      " [ 0  0  0  4  2]\n",
      " [ 0  3  2 10  0]\n",
      " [ 0  7  9  0 10]\n",
      " [ 0  0  2  2  3]]\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:13:04.475973Z",
     "start_time": "2025-07-16T17:13:04.463524Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 7：统计函数应用\n",
    "# 题目：某公司 6 个月的销售额（万元）为 [120, 135, 110, 125, 130, 140]。  \n",
    "# •\t计算销售额的总和、均值和方差。  \n",
    "# •\t找出销售额最高的月份和最低的月份。\n",
    "import numpy as np\n",
    "\n",
    "ar = np.array([120, 135, 110, 125, 130, 140])\n",
    "print(np.sum(ar))\n",
    "print(np.mean(ar))\n",
    "print(np.var(ar))\n",
    "print(np.sort(ar)[-1])\n",
    "print(np.argmax( ar))\n",
    "print(np.sort(ar)[0])\n",
    "print(np.argmin( ar))"
   ],
   "id": "429a2ab99c3004ee",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "760\n",
      "126.66666666666667\n",
      "97.22222222222223\n",
      "140\n",
      "5\n",
      "110\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:14:51.646114Z",
     "start_time": "2025-07-16T17:14:51.641590Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# \n",
    "# 题目 8：数组拼接\n",
    "# 题目：给定 A = [1, 2, 3] 和 B = [4, 5, 6]。  \n",
    "# •\t水平拼接为 [1, 2, 3, 4, 5, 6]。  \n",
    "# •\t垂直拼接为 [[1, 2, 3], [4, 5, 6]]。  \n",
    "# \n",
    "\n",
    "import numpy as np\n",
    "A = np.array([1, 2, 3])\n",
    "B = np.array([4, 5, 6])\n",
    "print(np.concatenate([A, B]))\n",
    "\n",
    "print(np.concatenate([A, B]).reshape(-1, 3))\n",
    "print(np.concatenate([A, B]).reshape(2, -1))\n",
    "print(np.stack([A, B])) #垂直拼接"
   ],
   "id": "eee6abe09047e2f0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5 6]\n",
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "[[1 2 3]\n",
      " [4 5 6]]\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:15:59.824686Z",
     "start_time": "2025-07-16T17:15:59.810992Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 9：唯一值与排序\n",
    "# 题目：给定数组 [2, 1, 2, 3, 1, 4, 3]。  \n",
    "# •\t找出唯一值并排序。  \n",
    "# •\t计算每个唯一值出现的次数。  \n",
    "import numpy as np\n",
    "ar = np.array([2, 1, 2, 3, 1, 4, 3])\n",
    "print(np.unique(ar))\n",
    "print(np.unique(ar, return_counts=True))"
   ],
   "id": "6b9ef56e98e97d71",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4]\n",
      "(array([1, 2, 3, 4]), array([2, 2, 2, 1]))\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-16T17:18:46.528182Z",
     "start_time": "2025-07-16T17:18:46.514652Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 题目 10：缺失值处理\n",
    "# 题目：给定数组 [1, np.nan, 3, np.nan, 5]。  \n",
    "# •\t计算非缺失值的数量。  \n",
    "# •\t将缺失值替换为 0。  \n",
    "import numpy as np\n",
    "ar = np.array([1, np.nan, 3, np.nan, 5])\n",
    "print(np.count_nonzero(~np.isnan(ar)))\n",
    "print(np.sum(~np.isnan(ar)))\n",
    "print(np.cumsum(np.where(np.isnan(ar), 0, 1))[-1])\n",
    "print(len(ar[~np.isnan(ar)])) # ~代表 非\n",
    "print(np.where(np.isnan(ar), 0, ar))"
   ],
   "id": "d41ef3de05591229",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "3\n",
      "3\n",
      "[1. 0. 3. 0. 5.]\n"
     ]
    }
   ],
   "execution_count": 30
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
